/**
 * @desc: 见证宝（老、大）用户补全资料
 * @author: binlety
 */

import { useState, useEffect, useMemo } from "react";
import { Form, Button, Radio, Input, Modal, Alert, message } from 'antd';
import CommonModal from "@/components/CommonModal";
import CommonLoading from '@/components/CommonLoading';
import CommonQinnvImgsLoad from '../../common/CommonQinnvImgsLoad';
import ComfortableTipsModal from '../../common/ComfortableTipsModal';
import { getCode } from '@/services/user';
import { submitAddDataOp } from '../service';
import styles from './index.module.less';

export const layout = {
  labelCol: {
    span: 5,
  },
  wrapperCol: {
    span: 16,
  }
};

const svg = <svg viewBox="64 64 896 896" focusable="false" data-icon="close-circle" width="1em" height="1em" fill="currentColor" aria-hidden="true"><path d="M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm165.4 618.2l-66-.3L512 563.4l-99.3 118.4-66.1.3c-4.4 0-8-3.5-8-8 0-1.9.7-3.7 1.9-5.2l130.1-155L340.5 359a8.32 8.32 0 01-1.9-5.2c0-4.4 3.6-8 8-8l66.1.3L512 464.6l99.3-118.4 66-.3c4.4 0 8 3.5 8 8 0 1.9-.7 3.7-1.9 5.2L553.5 514l130 155c1.2 1.5 1.9 3.3 1.9 5.2 0 4.4-3.6 8-8 8z"></path></svg>

const OriginOpenAccountModal = ({ handleOk, handleCancel }) => {

  const [form] = Form.useForm();

  const [step, setStep] = useState(1);
  const [accountType, setType] = useState(1);

  const [countDown, setCount] = useState(0);

  const [loading, setLoading] = useState(false);
  const [tipsMsg, setTipsMsg] = useState(null);//温馨提示弹窗

  const [topKey, setTopKey] = useState(0);
  const [leftKey, setLeftKey] = useState(0);
  const [rightKey, setRightKey] = useState(0);

  useEffect(() => {
    if (countDown) {
      setTimeout(() => {
        setCount(countDown - 1);
      }, 1000)
    }
  }, [countDown])

  const renderFooter = useMemo(() => {
    if (step == 1) {
      return (
        <>
          <Button key="cancel" onClick={handleCancel}>取消</Button>
          <Button key="next" onClick={() => setStep(2)} type='primary'>下一步</Button>
        </>
      )

    } else {
      return (
        <>
          <Button key="prev" onClick={() => setStep(1)}>上一步</Button>
          <Button key="sure" onClick={() => onSure('zhixingle')} type='primary'>确定</Button>
        </>
      )
    }
  }, [step])

  //图片上传回调手动更新表单值
  const handleDone = (type, res, file) => {
    const { success, data, msg } = res;
    if(success){
      const { creditCode, name, person, url,  cardNo, cardFrontUrl, cardBackUrl } = data || {};
      if(type == 'idCardFrontUrl'){
        form.setFieldsValue({
          idCardFrontUrl: cardFrontUrl,
          legalPersonName: name,
          idCard: cardNo
        });
      }else if(type == 'idCardBackUrl'){
        form.setFieldsValue({
          idCardBackUrl: cardBackUrl,
        });
      }else{
        form.setFieldsValue({
          licenseUrl: url,
          licenseName: name,
          legalPersonName: person,
          socialCreditCode: creditCode
        });
      }
    }else{
      setTipsMsg({
        type: 1,
        key: type,
        reason: msg
      })
    }
  };

  //获取验证码,并开始倒计时
  const handleGetCode = async () => {
    form.validateFields(['mobile']).then(async value => {
      setLoading(true);
      const res = await getCode({
        ...value,
        type: 9
      })
      setLoading(false);
      if (res.success) {
        setCount(59);
        message.success('验证码发送成功!');
      }
    })
  }

  const onSure = () => {
    // const content = <>
    //   <div style={{ backgroundColor: "", textAlign: "center", position: 'relative', top: '-20px', fontSize: '16px' }} className='common-color1'>温馨提示</div>
    //   <Alert message="身份资料验证失败" type="error" showIcon />
    //   <p style={{ marginTop: '6px' }}>原因为：请确认图片完整，保持光线充足，并且身份证在有效期内</p>
    // </>
    // Modal.info({
    //   content,
    //   icon: ''
    // })
    // return;

    form.validateFields().then(async value => {
      setLoading(true);
      const res = await submitAddDataOp({
        ...value
      })
      setLoading(false);
      if (res.success) {
        handleOk();
        message.success('补充资料成功！');
      }
    })
  }

  const renderErrorMsg = () => {
    const { type, reason } = errorMsg;
    if (type == 1) {
      return (<>
        <div className="common-color9" style={{ fontSize: '15px', display: 'flex', alignItems: "center", paddingLeft: '8px' }}>{svg}&nbsp;识别失败</div>
        <p style={{ marginTop: '2px', textIndent: '28px' }}>{reason}</p>
      </>)
    } else if (type == 2) {
      return (<>
        <Alert message="资料提交中" type="success" showIcon />
        <div style={{ fontSize: '16px', paddingLeft: '38px' }}>
          <p>银行正在验证资料，请等待几秒，不要退出！</p>
          <p>中途退出可能造成提交失败！</p>
          <img src="https://imgniu.zhaojiafang.com/front-web/ERP/shalou.gif" alt="" style={{ width: '200px', margin: '12px 0 0 95px' }} />
        </div>
      </>)
    } else {
      return (<>
        <div className="common-color9" style={{ fontSize: '15px', display: 'flex', alignItems: "center", paddingLeft: '8px' }}>{svg}&nbsp;身份资料验证失败</div>
        <p style={{ marginTop: '2px', textIndent: '28px' }}>原因为：{reason}</p>
      </>)
    }
  }

    //温馨提示modal
    const tipsModalProps = {
      tipsMsg,
      handleOk(){
        tipsMsg.key == 'licenseUrl' && setTopKey(leftKey + 1);
        tipsMsg.key == 'idCardFrontUrl' && setLeftKey(leftKey + 1);
        tipsMsg.key == 'idCardBackUrl' && setRightKey(rightKey + 1);
        setTipsMsg(null);
      }
    }

  return (
    <CommonModal
      title={step == 1 ? "选择类型" : "补充资料"}
      visible={true}
      onCancel={handleCancel}
      width={step == 1 ? 400 : 800}
      minHeight={step == 1 ? 120 : 200}
      footer={renderFooter}
    >
      {
        step == 1 ? (<>
          <div style={{ display: "flex", marginTop: '4px' }}>
            <span style={{ textIndent: "24px" }}>用户类型：</span>
            <Radio.Group onChange={(e) => setType(e.target.value)} value={accountType}>
              <Radio value={1}>个体工商户</Radio>
              <p style={{ height: '6px' }}></p>
              <Radio value={2} disabled>企业用户</Radio>
            </Radio.Group>
          </div>
          <p style={{ padding: '4px 0 0 94px', fontSize: '12px' }}>需要开通企业用户的请联系{APP_TITLE}技术</p>
        </>
        ) : (
          <>
            <Alert message='鉴于银行监管要求，以及不影响后续系统操作，需要您完善以下信息进行实名验证！' />

            <Form name='old-user-open-bank-account-form' form={form} {...layout} style={{ marginTop: '8px' }}>
              <Form.Item label="营业执照" rules={[{ required: true, message: '图片不能为空' }]}>
                <Form.Item name="licenseUrl" style={{ marginBottom: '0px' }}>
                  <CommonQinnvImgsLoad
                    key={topKey}
                    className="rectangleLarge"
                    actionUrl='/zjf-pays/imgOcr/license?type=1'
                    customText='上传营业执照'
                    handleOk={(val, file) => handleDone('licenseUrl', val, file)}
                    handleFailed={()=>setTopKey(topKey+1)}
                    customNode={<div className={`${styles.uploadWrap} ${styles.businessLiense}`} ><div className={styles.uploadIconBox}>+</div></div>}
                  />
                </Form.Item>
              </Form.Item>

              <Form.Item label={<span className="lable-require">身份证照片</span>}>
                <div style={{ display: 'flex' }}>
                  <div>
                    <Form.Item name="idCardFrontUrl" rules={[{ required: true, message: '图片不能为空' }]} style={{ marginBottom: '0px' }}>
                      <CommonQinnvImgsLoad
                        key={leftKey}
                        className="rectangleSmall"
                        actionUrl='/zjf-pays/imgOcr/cardFront'
                        customText='身份证人像面'
                        size={1}
                        handleOk={(val, file) => handleDone('idCardFrontUrl', val, file)}
                        handleFailed={()=>setLeftKey(leftKey+1)}
                        customNode={<div className={`${styles.uploadWrap} ${styles.identityFront}`} ><div className={styles.uploadIconBox}>+</div></div>}
                      />
                    </Form.Item>
                    <p style={{ textAlign: 'center' }}>身份证人像面</p>
                  </div>
                  <div>
                    <Form.Item name="idCardBackUrl" rules={[{ required: true, message: '图片不能为空' }]} style={{ marginBottom: '0px' }}>
                      <CommonQinnvImgsLoad
                        key={rightKey}
                        className="rectangleSmall"
                        actionUrl='/zjf-pays/imgOcr/cardBack'
                        customText='身份证国徽面'
                        size={1}
                        handleOk={(val, file) => handleDone('idCardBackUrl', val, file)}
                        handleFailed={()=>setRightKey(rightKey+1)}
                        customNode={<div className={`${styles.uploadWrap} ${styles.identityBack}`} ><div className={styles.uploadIconBox}>+</div></div>}
                      />
                    </Form.Item>
                    <p style={{ textAlign: 'center' }}>身份证国徽面</p>
                  </div>
                </div>
              </Form.Item>

              <Form.Item
                label="营业执照名称"
                name="licenseName"
                rules={[{ required: true, message: '请输入营业执照名称' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="社会统一信用代码"
                name="socialCreditCode"
                rules={[{ required: true, message: '请输入社会统一信用代码' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="法人姓名"
                name="legalPersonName"
                rules={[{ required: true, message: '请输入法人姓名' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="身份证号"
                name="idCard"
                rules={[{ required: true, message: '请输入身份证号' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="手机号"
                name="mobile"
                rules={[{ required: true, message: '请输入手机号' }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="手机验证码"
                name="smsCode"
                rules={[{ required: true, message: '请输入手机验证码' }]}
              >
                <div className="flex">
                  <Input />
                  <Button style={{ marginLeft: 24 }} onClick={handleGetCode} disabled={countDown}>获取验证码{countDown ? `(${countDown})` : ''}</Button>
                </div>
              </Form.Item>
            </Form>
          </>
        )
      }

       {/* 温馨提示 */}
       {tipsMsg && <ComfortableTipsModal { ...tipsModalProps} />}
       <CommonLoading loading={loading} />
    </CommonModal>
  )
}

export default OriginOpenAccountModal;